package tungsten.pb;

import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * Created by Lv on 2016/6/12.
 */
public class PBAdapter extends ChannelInitializer<SocketChannel>
{
    private ChannelInboundHandlerAdapter decoder;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast(new PBEncoder());

        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        if(decoder != null)
        {
            pipeline.addLast(decoder);
        }
    }

    public ChannelInboundHandlerAdapter setDecoder(ChannelInboundHandlerAdapter decoder)
    {
        this.decoder = decoder;
        return this;
    }
}